package org.jeecg.glr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.glr.domain.glr.GlrGateWayPatternDomain;
import org.jeecg.glr.entity.*;
import org.jeecg.glr.service.*;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.StringUtil;
import org.jeecg.glr.util.SunRiseSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

 /**
 * @Description: 网关模式关联表
 * @Author: jeecg-boot
 * @Date:   2020-03-10
 * @Version: V1.0
 */
@RestController
@RequestMapping("/glr/glrPatternGateway")
@Slf4j
public class GlrPatternGatewayController extends JeecgController<GlrPatternGateway, IGlrPatternGatewayService> {
	@Autowired
	private IGlrPatternGatewayService glrPatternGatewayService;
     @Autowired
     private IGlrPatternService glrPatternService;
	 @Autowired
	 private IGlrGatewayService glrGatewayService;

	 @Value("${glr.url.light_gateway_set_timefram}")
	 private String light_gateway_set_timefram;

	 @Autowired
	 private IGlrLightService glrLightService;


	 @Autowired
	 private IGlrProjectService glrProjectService;

	 @Resource
	 IGateWayCommon gateWayCommon;
	/**
	 * 分页列表查询
	 *
	 * @param glrPatternGateway
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(GlrPatternGateway glrPatternGateway,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GlrPatternGateway> queryWrapper = QueryGenerator.initQueryWrapperCode(glrPatternGateway, req.getParameterMap());
		Page<GlrPatternGateway> page = new Page<GlrPatternGateway>(pageNo, pageSize);
		IPage<GlrPatternGateway> pageList = glrPatternGatewayService.page(page, queryWrapper);
        List<GlrPatternGateway> list=pageList.getRecords();
        for (GlrPatternGateway p :
                list) {
           if(p.getType().equals(GLRConstant.GLR_LIGHT_POLE_DEVICE_04)){
			   GlrGateway gateway=glrGatewayService.getGlrGatewayByCode(p.getGateWayCode());
			   p.setGateWayName(gateway.getGatewayName());
			   GlrProject project=glrProjectService.getGlrProjectByCode(gateway.getProjectCode());
			   if(project!=null){
				   p.setGateWayName(project.getName()+"-"+p.getGateWayName());
			   }

		   }
			if(p.getType().equals(GLRConstant.GLR_LIGHT_POLE_DEVICE_03)){
				GlrLight glrLight=glrLightService.getById(p.getGateWayCode());
				p.setGateWayName(glrLight.getCode());
				if(StringUtil.isNotEmpty(glrLight.getProjectCode())){
					GlrProject project=glrProjectService.getGlrProjectByCode(glrLight.getProjectCode());
					if(project!=null){
						p.setGateWayName(project.getName()+"-"+p.getGateWayName());
					}
				}

			}
        }
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param glrPatternGateway
	 * @return
	 */
	@AutoLog(value = "添加模式",logType= CommonConstant.LOG_TYPE_2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody GlrPatternGateway glrPatternGateway) {
		glrPatternGatewayService.save(glrPatternGateway);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param glrPatternGateway
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody GlrPatternGateway glrPatternGateway) {
		glrPatternGatewayService.updateById(glrPatternGateway);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		glrPatternGatewayService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.glrPatternGatewayService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		GlrPatternGateway glrPatternGateway = glrPatternGatewayService.getById(id);
		if(glrPatternGateway==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(glrPatternGateway);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param glrPatternGateway
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GlrPatternGateway glrPatternGateway) {
        return super.exportXls(request, glrPatternGateway, GlrPatternGateway.class, "网关模式关联表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GlrPatternGateway.class);
    }

     /**
      * 分页列表查询
      *
      * @param glrPatternGateway
      * @param pageNo
      * @param pageSize
      * @param req
      * @return
      */
     @GetMapping(value = "/patternGateWayList")
     public Result<?> patternGateWayList(GlrPatternGateway glrPatternGateway,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
         QueryWrapper<GlrPatternGateway> queryWrapper = QueryGenerator.initQueryWrapper(glrPatternGateway, req.getParameterMap());
         Page<GlrPatternGateway> page = new Page<GlrPatternGateway>(pageNo, pageSize);
         IPage<GlrPatternGateway> pageList = glrPatternGatewayService.page(page, queryWrapper);
         Date dt = new Date();
         List<GlrPatternGateway> list=pageList.getRecords();
		 BigDecimal b_longitude=new BigDecimal("0");
		 BigDecimal b_latitude=new BigDecimal("0");

         for (GlrPatternGateway p :
                 list) {
			 GlrGateway gateway= glrGatewayService.getGlrGatewayByCode(p.getGateWayCode());
			 GlrPattern glrPattern= glrPatternService.getById(p.getPatternId());
			 if(!GLRConstant.YN_Y.equals(glrPattern.getSelfMotionYn())){
				 if(StringUtil.isNotEmpty(gateway.getLongitude())&&StringUtil.isNotEmpty(gateway.getLatitude())){
					 try{
						 b_longitude=new BigDecimal(gateway.getLongitude());
						 b_latitude=new BigDecimal(gateway.getLatitude());
					 }catch (Exception ex){

					 }
					 int timeb=0;
					 int timec=0;
					 if(StringUtil.isNotEmpty(glrPattern.getTimeb())){
						 timeb=Integer.parseInt(glrPattern.getTimeb());
					 }
					 if(StringUtil.isNotEmpty(glrPattern.getTimec())){
						 timec=Integer.parseInt(glrPattern.getTimec());
					 }
					 glrPattern.setSunupTime(SunRiseSet.getSunriseAddMinute(b_longitude,b_latitude,dt,timeb));
					 glrPattern.setSunsetTime(SunRiseSet.getSunsetAddMinute(b_longitude,b_latitude,dt,timec));
					 glrPattern.setSunupTime(SunRiseSet.getSunrise(b_longitude,b_latitude,dt));
					 glrPattern.setSunsetTime(SunRiseSet.getSunset(b_longitude,b_latitude,dt));
				 }
			 }else{
			 	String versionType=gateway.getGateWayCode().substring(0,4);
			 	if(GLRConstant.GLR_VERSION_TYPE_01_01.equals(versionType)||GLRConstant.GLR_VERSION_TYPE_03_01.equals(versionType)){
					try{
						b_longitude=new BigDecimal(gateway.getLongitude());
						b_latitude=new BigDecimal(gateway.getLatitude());
					}catch (Exception ex){

					}
					int timeb=0;
					int timec=0;
					if(StringUtil.isNotEmpty(glrPattern.getTimeb())){
						timeb=Integer.parseInt(glrPattern.getTimeb());
					}
					if(StringUtil.isNotEmpty(glrPattern.getTimec())){
						timec=Integer.parseInt(glrPattern.getTimec());
					}
					glrPattern.setSunupTime(SunRiseSet.getSunriseAddMinute(b_longitude,b_latitude,dt,timeb));
					glrPattern.setSunsetTime(SunRiseSet.getSunsetAddMinute(b_longitude,b_latitude,dt,timec));

				}else{

					glrPattern.setSunupTime(glrPattern.getCommandTimeb());
					glrPattern.setSunsetTime(glrPattern.getCommandTimec());
				}
			 }
             p.setGlrPattern(glrPattern);
         }
         return Result.ok(pageList);
     }
     /**
      * 分页列表查询
      *
      * @param pageNo
      * @param pageSize
      * @param req
      * @return
      */
     @GetMapping(value = "/patternList")
     public Result<?> patternList(GlrPattern glrPattern,
                                         @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                         @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                         HttpServletRequest req) {
         QueryWrapper<GlrPattern> queryWrapper = QueryGenerator.initQueryWrapperCode(glrPattern, req.getParameterMap());
         List<String> strList= glrPatternService.getPatternByGateWayCode(req.getParameter("gate_Way_Code"));
         if(strList!=null&&strList.size()>0){
             queryWrapper.notIn("id", strList);
         }
         Page<GlrPattern> page = new Page<GlrPattern>(pageNo, pageSize);
         IPage<GlrPattern> pageList = glrPatternService.page(page, queryWrapper);
         return Result.ok(pageList);
     }

	 /**
	  * 将模式和网关绑定
	  * @param glrPatternGateway
	  * @return
	  */
     @PostMapping(value = "/bingPattern")
     public Result<?> bingPattern(@RequestBody GlrPatternGateway glrPatternGateway) {
         glrPatternGatewayService.bingPattern(glrPatternGateway);
         return Result.ok("添加成功！");
     }

	 /**
	  * 网关模式应用
	  * @param glrPatternGateway
	  * @return
	  */
	 @PostMapping(value = "/usePattern")
	 public Result<?> usePattern(@RequestBody GlrPatternGateway glrPatternGateway) {
		 GlrPattern pattern=glrPatternService.getById(glrPatternGateway.getPatternId());
		 pattern.setGateWayCode(glrPatternGateway.getGateWayCode());
		 //GlrGateWayPatternDomain domain = new GlrGateWayPatternDomain();
		 //domain.setGateWayCode(glrPatternGateway.getGateWayCode());

		 /*
		 String timeFrams = "";
		 String luminances = "";
		 timeFrams = pattern.getCommandTimea() + "," + pattern.getTypeb()+pattern.getCommandTimeb() + "," + pattern.getTypec()+pattern.getCommandTimec() + ","
				 + pattern.getCommandTimed() + "," + pattern.getCommandTimee();
		 luminances = pattern.getBrightValuea() + "," + pattern.getBrightValueb() + "," + pattern.getBrightValuec() + ","
				 + pattern.getBrightValued() + "," + pattern.getBrightValuee();

		 domain.setLuminance(luminances);
		 domain.setTimeFrame(timeFrams.replace(":",""));
		 */
		 pattern.setCommandTimea(pattern.getCommandTimea().replace(":",""));
         pattern.setCommandTimeb(pattern.getCommandTimeb().replace(":",""));
         pattern.setCommandTimec(pattern.getCommandTimec().replace(":",""));
         pattern.setCommandTimed(pattern.getCommandTimed().replace(":",""));
         pattern.setCommandTimee(pattern.getCommandTimee().replace(":",""));
         if(StringUtil.isNotEmpty(pattern.getSelfMotionYn())&&GLRConstant.YN_Y.equals(pattern.getSelfMotionYn())){
         	pattern.setSelfMotionYn("1");
		 }else{
			 pattern.setSelfMotionYn("0");
		 }
		 Boolean flag= gateWayCommon.setTimeFrameAndDimming(pattern);
		 if(flag){
			 glrPatternGateway.setCurrentStatus(GLRConstant.YN_Y);
			 glrPatternGatewayService.updateById(glrPatternGateway);
		//	 glrGatewayService.getGlrGatewayByCode(glrPatternGateway.getGateWayCode());
			 return Result.ok("操作成功！");
		 }
		 return Result.ok("操作失败！");
	 }

	 /**
	  * 分页列表查询
	  *
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/patternGatewayList")
	 public Result<?> patternGatewayList(GlrPatternGateway glrPatternGateway,
								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								  HttpServletRequest req) {
		 QueryWrapper<GlrPatternGateway> queryWrapper = QueryGenerator.initQueryWrapper(glrPatternGateway, req.getParameterMap());
		 Page<GlrPatternGateway> page = new Page<GlrPatternGateway>(pageNo, pageSize);
		 IPage<GlrPatternGateway> pageList = glrPatternGatewayService.page(page, queryWrapper);
		 return Result.ok(pageList);
	 }


	 /**
	  * 分页列表查询
	  *
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/patternBindingGatewayList")
	 public Result<?> patternBindingGatewayList(GlrGateway glrGateway,
												@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												HttpServletRequest req) {
		 QueryWrapper<GlrGateway> queryWrapper = QueryGenerator.initQueryWrapperCode(glrGateway, req.getParameterMap());
		 List<String> strList= glrPatternGatewayService.getPatternByGateWayCode(req.getParameter("patternId"),GLRConstant.GLR_LIGHT_POLE_DEVICE_04);
		 if(strList!=null&&strList.size()>0){
			 queryWrapper.notIn("gate_way_code", strList);
		 }
		 Page<GlrGateway> page = new Page<GlrGateway>(pageNo, pageSize);
		 IPage<GlrGateway> pageList = glrGatewayService.page(page, queryWrapper);
		 return Result.ok(pageList);
	 }

	 /**
	  * 分页列表查询
	  *
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @GetMapping(value = "/patternBindingLightList")
	 public Result<?> patternBindingLightList(GlrLight glrLight,
												@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												HttpServletRequest req) {
		 QueryWrapper<GlrLight> queryWrapper = QueryGenerator.initQueryWrapperCode(glrLight, req.getParameterMap());
		 List<String> strList= glrPatternGatewayService.getPatternByGateWayCode(req.getParameter("patternId"),GLRConstant.GLR_LIGHT_POLE_DEVICE_03);
		 if(strList!=null&&strList.size()>0){
			 queryWrapper.notIn("gate_way_code", strList);
		 }
		 Page<GlrLight> page = new Page<GlrLight>(pageNo, pageSize);
		 IPage<GlrLight> pageList = glrLightService.page(page, queryWrapper);
		 List<GlrLight> list= pageList.getRecords();
		 for (GlrLight lg:
			  list) {
		 	if(StringUtil.isNotEmpty(lg.getProjectCode())){
				GlrProject project= glrProjectService.getGlrProjectByCode(lg.getProjectCode());
				if(project!=null){
					lg.setProjectName(project.getName());
				}
			}
		 }
		 return Result.ok(pageList);
	 }





	 /**
	  * 将模式和网关绑定
	  * @param glrPatternGateway
	  * @return
	  */
	 @PostMapping(value = "/bingPatternGateWay")
	 public Result<?> bingPatternGateWay(@RequestBody GlrPatternGateway glrPatternGateway) {
		 glrPatternGatewayService.bingPatternGateWay(glrPatternGateway);
		 return Result.ok("添加成功！");
	 }

	 /**
	  * 将模式和网关绑定
	  * @param glrPatternGateway
	  * @return
	  */
	 @PostMapping(value = "/bingPatternLight")
	 public Result<?> bingPatternLight(@RequestBody GlrPatternGateway glrPatternGateway) {
		 glrPatternGatewayService.bingPatternGateWay(glrPatternGateway);
		 return Result.ok("添加成功！");
	 }
}
